$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

var options={
	height:'full-155',
	page:{curr:1},
	id:'id',
	limit:10,
	path:'',
	url:'',
	winWidth:'500px',
	postData:{},
	addurl:'add',
	editurl:'edit',
	delurl:'delete',
	searchurl: 'search',
	viewurl: 'view',
	toolbar: 'default',
	done:function(res,curr,count){
		//console.info(res.data[0].LAY_TABLE_INDEX);
		//console.info(curr);
		//console.info(count);
		//if(rowId){
		//	var ss='tr[data-index='+rowId+']';
		//	$(ss).addClass('selected');
		//}

	}
}
var tableData=null;
var table=null;
var treetable=null;
var LayUiTable=function(data,rowId,limit,page){
	var that=this,$=layui.$,tableIns;
	this.currRow=null; //当前行idx
	this.crId=null;  //当前行ID
	this.currObj=null;
	var options2={};
	
	if(limit){
		options2.limit=limit;
		options2.page={curr:page};
	}
	
	this.ops=$.extend({},options,data,options2);
	//$.extend(options,data);
	if(!this.ops.url){
		this.ops.url=this.ops.path+'/page';
	}
	this.ops.url=this.ops.url+"?sort="+(this.ops.sort?this.ops.sort:'createDate');
	this.ops.url=this.ops.url+"&order="+(this.ops.order?this.ops.order:'ASC');
	//this.ops.where=this.ops.postData;
	/***
	 * 取ID值所对应的行的值
	 */
	this.getRowData=function(id){
		for(var i=0;i<tableData.length;i++){
			var x=tableData[i];
			if(x.id==id){
				return x;
			}
		}
		return null;
	}
	
	this.getRowIdx=function(id){
		var rowData=that.getRowData(id);
		return rowData?rowData.LAY_TABLE_INDEX:null;
	}
	/**
	 * 获取当前行数据
	 * 
	 */
	this.getCurrRowData=function(){
		if(that.crId){
			for(var i=0;i<tableData.length;i++){
				var x=tableData[i];
				if(x.id==that.crId){
					return x;
				}
			}
		}
		return null;
	}
	
	this.init=function(){
		layui.use(['table','treetable'],function(){
			table=layui.table;
			treetable=layui.treetable;
			//修改表格渲染好的回调函数
			that.ops.done=function(res){
				tableData=res.data; //将表格的所有数据装载到tableData中
				$('tr').removeClass('selected');
				if(rowId){
					var crow=that.getRowData(rowId);
					if(!crow){
						that.currRow=null;
						that.crId=null;
						return;
					}
					var crId=crow.LAY_TABLE_INDEX;
					var ss='tr[data-index='+crId+']';
					$(ss).addClass('selected');
					that.currRow=crId;
					that.crId=rowId;
				}else{
					that.currRow=null;
					that.crId=null;
				}
			};
			
			tableIns=table.render(that.ops); //渲染表格
			
			//表格的选中行事件处理
			table.on('row',function(obj){
				if(that.currRow&&that.currRow==obj.tr.attr('data-index')){
					that.currRow=null;
					that.crID=null;
					obj.tr.removeClass('selected');
				}else{
					that.currRow=obj.tr.attr('data-index');
					that.crId=obj.data.id;
					obj.tr.addClass('selected').siblings().removeClass('selected');
				}
			});
			
			table.on('rowDouble',function(obj){
				obj.tr.removeClass('selected');
				that.currRow=obj.tr.attr('data-index');
				that.crId=obj.data.id;
				obj.tr.addClass('selected').siblings().removeClass('selected');
				that.view();
			});
			
			//表格的工具栏事件处理
			table.on('toolbar',function(obj){
				switch(obj.event){
				case 'add_panel':
					that.add_panel();
					break;
				case 'update_panel':
					that.edit_panel();
					break;
				case 'add':
					that.add();
					break;
				case 'delete':
					that.del();
					break;
				case 'update':
					that.edit();
					break;
				case 'search':
					that.search2();
					break;
				case 'view':
					that.view();
					break;
				case 'derive':
					that.derive();
					break;
				case 'template':
					that.template();
					break;
				case 'lead':
					that.lead();
				}
			});
			table.on('tool', function(obj){
				var id = obj.data.id;
				if(obj.event === 'update_panel2'){
					that.update_panel2(id);
				}else if(obj.event === "delete2"){
					that.delete2(id);
				}else if(obj.event === "view2"){
					that.view2(id);
				}else if(obj.event === "view3"){
					that.view3(id);
				}else if(obj.event === 'certificate'){
					that.certificate(id);
				}
			});
		});
	}
	
	//取当前页码
	this.getPage=function(){
		var page=$(".layui-laypage-skip").find("input").val();
		return page==undefined?1: page;
	}
	
	//取每页记录数
	this.getLimit=function(){
		var limit = $(".layui-laypage-limits").find("option:selected").val();
		return limit == undefined? 10: limit;
	}
	
	this.refresh=function(){
		var page=that.getPage();
		var limit=that.getLimit();
		var url=that.ops.path+(that.ops.path.length>0?'/':'')+'manage';
		if(that.currRow){
			$('#content').load(url+'?limit='+limit+'&page='+page+'&currRow='+that.crId,that.ops.where);
		}else{
			$('#content').load(url+'?limit='+limit+'&page='+page,that.ops.where);
		}
	}
	
	//用panel进行新增操作
	this.add_panel=function(){
		var addurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.addurl;
		var saveurl=that.ops.path+(that.ops.path.length>0?'/':'')+'save';
		var page = $(".layui-laypage-skip").find("input").val();
 		var limit = $(".layui-laypage-limits").find("option:selected").val();
 		page = page==undefined?1: page;
 		limit = limit == undefined? 10: limit;
 		var subDiv=$('<div class="layui-form-item" style="text-align: right;"><button class="layui-btn" lay-submit lay-filter="formVerify">立即提交</button><button type="reset" class="layui-btn layui-btn-primary">重置</button><button id="closeBtn" type="button" class="layui-btn layui-btn-primary">返回</button></div>');
		$.get(addurl,function(data){
			//data.append(subDiv);
			$('#content').html(data);
			$('#content').find('form').append(subDiv);
			$('#closeBtn').click(function(){
				$('#content').load(that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page,that.ops.where);
			});
			layui.use('form',function(){
				var form=layui.form;
				form.on('submit(formVerify)',function(data){
					$.post(saveurl,data.field,function(result){
						if(result.success){
							$('#content').load(that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page,that.ops.where);
						}else{
							layer.msg(result.msg,{offset:'rb'});
						}
					});
					return false;
				});
			});
			
		});
	}
	
	//用弹窗进行新增操作
	this.add=function(){
		var addurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.addurl;
		var saveurl=that.ops.path+(that.ops.path.length>0?'/':'')+'save';
		$.get(addurl,that.ops.postData,function(data){
		      layer.open({
		    	  id:'add',
		    	  type:1,
		    	  title:'新增',
		    	  area: that.ops.winWidth,
		    	  content:data,
		    	  btn:['提交','退出'],
		    	  success:function(layero,index){
		    		  layui.use('form',function(){
		    			 var form=layui.form;
		    			 layero.addClass('layui-form');
		    			 var submitBtn=layero.find('.layui-layer-btn0');
		    			 submitBtn.attr('lay-filter','formVerify').attr('lay-submit','');
		    			 layero.keydown(function(e){
		    				 if(e.keyCode==13){
		    					 submitBtn.click();
		    				 }
		    			 });
		    			 
		    			 form.on('submit(formVerify)',function(data){
		    				$.post(saveurl,data.field,function(result){
		    					if(result.success){
		    						that.currRow=null;
		    						layer.close(index);
		    						table.reload('id',{toolbar:'default',where:that.ops.postData});
		    					}
		    					layer.msg(result.msg,{offset:'rb'});
		    				});
		    				return false;
		    			 });
		    		  });
		    	  }
		      });
	 		  
	 	  },'html');
	};
	
	//用页面跳转进行修改操作
	this.edit_panel=function(){
		var editurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.editurl;
		var saveurl=that.ops.path+(that.ops.path.length>0?'/':'')+'save';
		var page = $(".layui-laypage-skip").find("input").val();
 		var limit = $(".layui-laypage-limits").find("option:selected").val();
 		page = page==undefined?1: page;
 		limit = limit == undefined? 10: limit;
		if(that.crId){
			var postData=$.extend({},that.ops.postData,{id:that.crId});
			$.get(editurl,postData,function(html){
				var subDiv=$('<div class="layui-form-item" style="text-align: right;"><button class="layui-btn" lay-submit lay-filter="formVerify">立即提交</button><button type="reset" class="layui-btn layui-btn-primary">重置</button><button id="closeBtn" type="button" class="layui-btn layui-btn-primary">返回</button></div>');
				$('#content').html(html);
				$('#content').find('form').append(subDiv);
				$('#closeBtn').click(function(){
					page=that.getPage();
					limit=that.getLimit();
					$('#content').load(that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page+'&currRow='+that.crId,that.ops.where);
				});
				layui.use('form',function(){
					var form=layui.form;
					form.on('submit(formVerify)',function(data){
						$.post(saveurl,data.field,function(result){
							if(result.success){
								$('#content').load(that.ops.path+(that.ops.path.length>0?'/':'')+'manage?currRow='+that.crId+'&limit='+limit+'&page='+page,that.ops.where);
							}else{
								layer.msg(result.msg,{offset:'rb'});
							}
						});
						return false;
					});
				});
				
			});
		}else{
      		layer.alert('请先选择一行数据再进行修改操作！');
      	}
	}
	
	//右边按钮修改
	this.update_panel2 = function(id){
		var editurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.editurl;
		var saveurl=that.ops.path+(that.ops.path.length>0?'/':'')+'save';
		var page = $(".layui-laypage-skip").find("input").val();
 		var limit = $(".layui-laypage-limits").find("option:selected").val();
 		page = page==undefined?1: page;
 		limit = limit == undefined? 10: limit;
		var postData=$.extend({},that.ops.postData,{id:id});
		$.get(editurl,postData,function(html){
			var subDiv=$('<div class="layui-form-item" style="text-align: right;"><button class="layui-btn" lay-submit lay-filter="formVerify">立即提交</button><button type="reset" class="layui-btn layui-btn-primary">重置</button><button id="closeBtn" type="button" class="layui-btn layui-btn-primary">返回</button></div>');
			$('#content').html(html);
			$('#content').find('form').append(subDiv);
			$('#closeBtn').click(function(){
				page=that.getPage();
				limit=that.getLimit();
				$('#content').load(that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page+'&currRow='+that.crId,that.ops.where);
			});
			layui.use('form',function(){
				var form=layui.form;
				form.on('submit(formVerify)',function(data){
					$.post(saveurl,data.field,function(result){
						if(result.success){
							$('#content').load(that.ops.path+(that.ops.path.length>0?'/':'')+'manage?currRow='+that.crId+'&limit='+limit+'&page='+page,that.ops.where);
						}else{
							layer.msg(result.msg,{offset:'rb'});
						}
					});
					return false;
				});
			});
			
		});
	}
	
	//右边按钮删除
	this.delete2=function(id){
		var delurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.delurl;
    	layer.confirm('真的删除行么?', function(index){
    	    //向服务端发送删除指令
    	  	$.post(delurl,{id:id},function(data){
	    	  	if(data.success){
	    	  		layer.close(index);
  					var page=that.getPage();
					var limit=that.getLimit();
					$('#content').load(that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page,that.ops.where);
	    	  		//that.currRow.del(); //删除对应行（tr）的DOM结构，并更新缓存
	    	  	}
	    	  	layer.msg(data.msg,{offset:'rb'});			    	  		
    	  	}); 
      	});
	};
	
	//修改操作
	this.edit=function(){
		var editurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.editurl;
		var saveurl=that.ops.path+(that.ops.path.length>0?'/':'')+'save';
		var postData=$.extend({},that.ops.postData,{id:that.crId});
      	if(that.currRow){
      		$.get(editurl,postData,function(html){
			      layer.open({
			    	  id:'user1',
			    	  type:1,
			    	  shadeClose:true,
			    	  area: that.ops.winWidth,
			    	  title:'修改',
			    	  content:html,
			    	  btn:['提交','退出'],
			    	  //弹出层打开成功的回调
			    	  success:function(layero,index){
			    		  layui.use('form',function(){
			    			  var form=layui.form;
			    			  //让‘提交’按钮有提交功能
				    		  layero.addClass('layui-form');
				    		  var submitBtn=layero.find('.layui-layer-btn0');
				    		  submitBtn.attr('lay-filter','formVerify').attr('lay-submit','');
				    		  //在弹出层里绑定回车就提交表单
				    		  layero.keydown(function(e){
				    			 if(e.keyCode==13){
				    				 submitBtn.click();
				    			 }
				    		  });
				    		  //表单
				    		  //form.render();
				    		  
				    		  //绑定表单提交事件，先校验，通过就ajax提交
				    		  form.on('submit(formVerify)',function(data){
				    			  $.post(saveurl,data.field,function(result){
				    				  if(result.success){
				    					  that.currRow=null;
				    					  table.reload('id',{toolbar: 'default',where:that.ops.postData});
				    					  tableIns.reload();
				    					  layer.close(index);
				    				  }
				    				  layer.msg(result.msg,{offset:'rb'});
				    			  });
				    			  return false;
				    		  });
			    		  });
			    	  },
			      });
      			
      		},'html');
      	}else{
      		layer.alert('请先选择一行数据再进行修改操作！');
      	}
	};
	//删除事件
	this.del=function(){
		var delurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.delurl;
	      if(that.currRow){
	    	  layer.confirm('真的删除行么?', function(index){
	    	    //向服务端发送删除指令
	    	  	$.post(delurl,{id:that.crId},function(data){
		    	  	if(data.success){
		    	  		layer.close(index);
	  					var page=that.getPage();
						var limit=that.getLimit();
						$('#content').load(that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page,that.ops.where);
		    	  		//that.currRow.del(); //删除对应行（tr）的DOM结构，并更新缓存
		    	  	}
		    	  	layer.msg(data.msg,{offset:'rb'});			    	  		
	    	  	}); 
	      	});
	      }else{
	    	  layer.alert('请先选择一条数据再进行删除操作！');
	      }
	};
	
	this.search2=function(){
		var searchurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.searchurl;
		$.get(searchurl,that.ops.where,function(data){
			layer.open({
		    	  id:'add',
		    	  type:1,
		    	  title:'新增',
		    	  area: that.ops.winWidth,
		    	  content:data,
		    	  btn:['查询','清除查询条件','退出'],
		    	  btn2:function(index,layero){
		    		  that.ops.where={};
		    		  $('form')[0].reset();
		    		  that.currRow=null;
		    		  that.refresh();
		    	  },
		    	  success:function(layero,index){
		    		  layui.use('form',function(){
		    			 var form=layui.form;
		    			 // 让‘提交’按钮有提交功能
		    			 layero.addClass('layui-form');
			    		 var submitBtn=layero.find('.layui-layer-btn0');
			    		 submitBtn.attr('lay-filter','formVerify').attr('lay-submit','');
			    		  //在弹出层里绑定回车就提交表单
			    		  layero.keydown(function(e){
			    			 if(e.keyCode==13){
			    				 submitBtn.click();
			    			 }
			    		  });
			    		  //绑定表单提交事件，先校验，通过就ajax提交
			    		  form.on('submit(formVerify)',function(data2){
			    			  that.ops.where=data2.field;
			    			  table.reload('id',{where:that.ops.where});
			    			  layer.close(index);
			    			  return false;
			    		  });

		    		  });
		    	  }
			});
		});
	};
	
	this.view=function(){
		var editurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.editurl;
		if(that.currRow){
			//向服务端发送删除指令
			var page=that.getPage();
			var limit=that.getLimit();
			var url=that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page+'&currRow='+that.crId;
		    console.info(url);
			$.post(editurl,{id:that.crId},function(html){
		    	$('#content').html(html);
		    	$('input').attr('readonly',true);
		    	$('input').attr('placeholder','');
		    	//$('form input').removeClass('layui-unselect');
		    	$('form div.layui-form-select,form div.layui-select-title').off();
		    	var div=$('<div class="layui-form-item"/>');
		    	var label=$('<label class="layui-form-label"/>');
				//var a=$('<a href="javascript:;"/>').html('返回');
				var a=$('<button class="layui-btn layui-btn-primary" type="button">返回</button>')
		    	label.append(a);
				div.append(label);
				$('form').append(div);
				a.click(function(){
					$('#content').load(url,that.ops.where);
				});
		    },'html');
		}else{
			layer.alert('请先选择一条数据再进行删除操作！');
		}
	}
	
	this.derive=function(){
		var bjid=$("#bjid").val();
		window.location.href="student/derive?id="+bjid;
	}
	
	this.template=function(){
		window.location.href="static/template/结业证书模板.docx";
	}
	
	this.lead = function(){
		$.post("student/lead", function(data){
			layui.use('layer', function(){
				var lay = layer.open({
					title: '上传结业证书',
					type: 1,
					shade: 0.3,
					content: data,
					area: ['360px', '220px'],
					btn: ['导入', '取消'],
					yes:function(){
						var file = $("#uploadFile")[0].files[0];
						var formData = new FormData();
						var tbClassId = $("#bjid").val();
		        		formData.append("files", file);
		        		formData.append("tbClassId", tbClassId);
		        		$.ajax({
				   			type:"post",   
				   			url:"student/updateLead",
				   			data: formData,
				   		    processData: false,
				   		    contentType: false,
				   			mimeType:"multipart/form-data",
				   		 	success:function(data){
				   		 		layer.msg(data);
				   		 		layer.close(lay);
				   		 		table.reload('stu',{url : 'student/page'});
				   		 	}
		        		})
      				}
				})
			})
		})
	}
	
	this.view2=function(id){
		var editurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.editurl;
		//向服务端发送删除指令
		var page=that.getPage();
		var limit=that.getLimit();
		var url=that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page+'&currRow='+that.crId;
	    console.info(url);
		$.post(editurl,{id:id},function(html){
	    	$('#content').html(html);
	    	$('input').attr('readonly',true);
	    	$('input').attr('placeholder','');
	    	//$('form input').removeClass('layui-unselect');
	    	$('form div.layui-form-select,form div.layui-select-title').off();
	    	var div=$('<div class="layui-form-item"/>');
	    	var label=$('<label class="layui-form-label"/>');
			//var a=$('<a href="javascript:;"/>').html('返回');
			var a=$('<button class="layui-btn layui-btn-primary" type="button">返回</button>')
	    	label.append(a);
			div.append(label);
			$('form').append(div);
			a.click(function(){
				$('#content').load(url,that.ops.where);
			});
	    },'html');
	}
	
	this.view3=function(id){
		var editurl=that.ops.path+(that.ops.path.length>0?'/':'')+that.ops.viewurl;
		//向服务端发送删除指令
		var page=that.getPage();
		var limit=that.getLimit();
		var url=that.ops.path+(that.ops.path.length>0?'/':'')+'manage?limit='+limit+'&page='+page+'&currRow='+that.crId;
	    console.info(url);
		$.post(editurl,{id:id},function(html){
	    	$('#content').html(html);
	    	$('input').attr('readonly',true);
	    	$('input').attr('placeholder','');
	    	//$('form input').removeClass('layui-unselect');
	    	$('form div.layui-form-select,form div.layui-select-title').off();
	    	var div=$('<div class="layui-form-item"/>');
	    	var label=$('<label class="layui-form-label"/>');
			//var a=$('<a href="javascript:;"/>').html('返回');
			var a=$('<button class="layui-btn layui-btn-primary" type="button">返回</button>')
	    	label.append(a);
			div.append(label);
			$('form').append(div);
			a.click(function(){
				$('#content').load(url,that.ops.where);
			});
	    },'html');
	}
	
	//清空查询
	this.empty = function (){
		$("#myForm input,textarea,select").val("");
		that.ops.where = '';
		table.reload(that.ops.id,{where: ''});
	}


	//查询
	this.search = function (){
		that.ops.where=$("#myForm").serializeObject();
		table.reload(that.ops.id,{where:that.ops.where});
	}
	
	//上传结业证书
	this.certificate = function(id){
		$.post("student/certificate", {id: id}, function(data){
			layui.use('layer', function(){
				layer.open({
					title: '上传结业证书',
					type: 1,
					shade: 0.3,
					maxmin: true,
					content: data,
					area: ['300px', '330px'],
					btn: ['上传', '取消'],
					yes:function(){
      				},
      				//弹出层打开回调
      				success: function(layero, index){
      					layui.use('form', function(){
      						var form=layui.form;
			    			layero.addClass('layui-form');
				    		var submitBtn=layero.find('.layui-layer-btn0');
				    		submitBtn.attr('lay-filter','formVerify').attr('lay-submit','');
				    		layero.keydown(function(e){
					    		if(e.keyCode==13){
					    			submitBtn.click();
					    		}
					    	});
				    		form.on('submit(formVerify)',function(data){
				    			$.post("student/updateCertificate", data.field, function(result){
			    					layer.msg("上传成功",{offset:'rb'});
			    					layer.close(index);
    	      					});
				    		});
      					})
      				}
				})
			})
		})
	}
}